package br.fatec.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Log 
{
	public static void gravarLog(Exception ex)
	{
		try
		{
			StringWriter sw = new StringWriter();
			ex.printStackTrace(new PrintWriter(sw));
			String linhas[] = sw.toString().split("\n");
			String mensagem = linhas[0] + " - " + linhas[1];
			
			gravarLog(mensagem.replace("\r", "").replace("\t", ""));
		}		
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public static void gravarLog(String mensagem)
	{
		try
		{
			File arqLog = getArquivo();
			if (arqLog == null)
				return;
			
			FileWriter fw = new FileWriter(arqLog, true);
			BufferedWriter bw = new BufferedWriter(fw);
			SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy - hh:mm:ss");
			Date dataAtual = new Date(System.currentTimeMillis());
			bw.write("Flamel - " + format.format(dataAtual) + " - " + mensagem + "\n");
			bw.close();
			fw.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	private static File getArquivo()
	{
		try
		{
			File arqLog = new File("..\\Flamel\\Log");
			if (!arqLog.exists())
			{
				if (!arqLog.mkdir())
					return null;
			}
			
			SimpleDateFormat format = new SimpleDateFormat("MM-yyyy");
			Date dataAtual = new Date(System.currentTimeMillis());
			arqLog = new File("..\\Flamel\\Log\\Log - " + format.format(dataAtual) + ".txt");
			if (!arqLog.exists())
			{
				if (!arqLog.createNewFile())
					return null;
			}			
			
			return arqLog;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
}
